import 'dart:async';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/system_ui_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'building_index_view_model.dart';

/// 创建楼层中的企业
class CreateFloorCompanyPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CreateFloorCompanyPage";
  //创建还是编辑 00创建 01编辑
  final String createOrEdit;
  final String floorName;
  final String buildingIndexId;
  final FloorCompanyListBean companyInfo;
  final ComWbrandBean comWbrandBean;
  const CreateFloorCompanyPage(
      {Key key, this.createOrEdit, this.floorName,
        this.buildingIndexId, this.companyInfo, this.comWbrandBean}) : super(key:key);

  @override
  _CreateFloorCompanyPageState createState() => _CreateFloorCompanyPageState();
  static Future<dynamic> navigatorPush(BuildContext context, String createOrEdit,
      {String floorName, String buildingIndexId, FloorCompanyListBean companyInfo,
        ComWbrandBean comWbrandBean}){
    return RouterUtils.routeForFutureResult(
        context,
        CreateFloorCompanyPage(
          createOrEdit: createOrEdit,
          floorName: floorName,
          buildingIndexId: buildingIndexId,
          companyInfo: companyInfo,
          comWbrandBean: comWbrandBean,
        ),
        routeName: CreateFloorCompanyPage.ROUTER
    );
  }
}

class _CreateFloorCompanyPageState
    extends BaseState<CreateFloorCompanyPage> {

  TextEditingController _houseNumberController;
  TextEditingController _companyNameController;

  //楼层数 默认1F
  String _floor = "1F";
  //门牌号码
  String _houseNumber;
  //企业名称
  String _companyName;

  BuildingIndexViewModel _viewModel;

  //编辑用到的企业信息
  FloorCompanyListBean _companyInfo;
  //水牌信息
  ComWbrandBean _comWbrandBean;

  @override
  void initState() {
    super.initState();
    _comWbrandBean = widget?.comWbrandBean;
    _viewModel = new BuildingIndexViewModel(this);

    if("00" == widget?.createOrEdit){
      //创建
      if(StringUtils.isNotEmpty(widget?.floorName)){
        _floor = widget?.floorName;
      }
    }else{
      //编辑
      _companyInfo = widget?.companyInfo;
      if(_companyInfo != null){
        //floorflg 01地下 02地上
        if("02" == _companyInfo.floorflg){
          _floor = _companyInfo.fnum + "F";
        }else{
          _floor = "B" + _companyInfo.fnum;
        }
        _houseNumber = _companyInfo.hnum??"";
        _companyName = _companyInfo.company??"";
      }
    }
    _houseNumberController = TextEditingController(text: _houseNumber??"")
      ..addListener(() => _notifyChange());
    _companyNameController = TextEditingController(text: _companyName??"")
      ..addListener(() => _notifyChange());
  }

  @override
  void dispose() {
    super.dispose();
    _companyNameController.clear();
    _houseNumberController.clear();
    _companyNameController.dispose();
    _houseNumberController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toFloorWidget(),
        _toHouseNumberWidget(),
        _toCompanyInfoWidget(),
        SizedBox(height: 30,),
        _toCreateWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title:  ("00" == widget?.createOrEdit)?"添加企业":"编辑企业",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }


  ///所在楼层
  Widget _toFloorWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        return SelectUtil.showListSelectDialog(
          context: context,
          title: "选择楼层",
          positionStr: _floor,
          textList: getFloorList(),
          onSelect: (String value) {
            _floor = value;
            setState(() {});
          },
          bgColor: Colors.white,
          titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          itemColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        );
          // if(_floor.contains("F")){
          //   return SelectUtil.showListSelectDialog(
          //       context: context,
          //       title: "选择楼层",
          //       positionStr: _floor,
          //       textList: getUpFloor(),
          //       onSelect: (String value) {
          //         _floor = value;
          //         setState(() {});
          //       },
          //     bgColor: Colors.white,
          //     titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          //     itemColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          //   );
          // }else if(_floor.contains("B")){
          //   return SelectUtil.showListSelectDialog(
          //       context: context,
          //       title: "选择楼层",
          //       positionStr: _floor,
          //       textList: getDownFloor(),
          //       onSelect: (String value) {
          //         _floor = value;
          //         setState(() {});
          //       },
          //     bgColor: Colors.white,
          //     titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          //     itemColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          //   );
          // }
      },
      child: Container(
        height: 51,
        color: Colors.white,
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15),
              height: 50,
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  Text(
                    "所在楼层",
                    style: TextStyle(
                        fontSize: 14,
                        color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
                    ),
                  ),
                  SizedBox(width: 15,),
                  Text(
                    _floor,
                    style: TextStyle(
                        fontSize: 14,
                        color: ThemeRepository.getInstance().getCardBgColor_21263C()
                    ),
                  ),
                  Spacer(),
                  Image.asset(
                    "images/icon_arrow_right_grey.png",
                    width: 6,
                  )
                ],
              ),
            ),
            Container(
              height: 1,
              margin: EdgeInsets.only(left: 15),
              color: Color(0xFFEEEEEE),
            )
          ],
        ),
      ),
    );
  }

  ///门牌号码
  Widget _toHouseNumberWidget(){
    return Container(
      height: 51,
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 15),
            height: 50,
            alignment: Alignment.centerLeft,
            child: Row(
              children: [
                Text(
                  "门牌号码",
                  style: TextStyle(
                    fontSize: 14,
                    color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                  ),
                ),
                SizedBox(width: 15,),
                Expanded(
                  child: VgTextField(
                    controller: _houseNumberController,
                    keyboardType: TextInputType.text,
                    style: TextStyle(
                        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                        fontSize: 14),
                    decoration: new InputDecoration(
                        counterText: "",
                        hintText: "选填",
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                            fontSize: 14,
                            color: Color(0XFFB0B3BF))),
                    inputFormatters: <TextInputFormatter> [
                      FilteringTextInputFormatter(RegExp("[A-Za-z0-9+]"), allow: true),
                      LengthLimitingTextInputFormatter(5)
                    ],
                    maxLines: 1,
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: 1,
            margin: EdgeInsets.only(left: 15),
            color: Color(0xFFEEEEEE),
          )
        ],
      ),
    );
  }

  ///企业名称
  Widget _toCompanyInfoWidget(){
    return Container(
      height: 51,
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 15),
            height: 50,
            alignment: Alignment.centerLeft,
            child: Row(
              children: [
                Text(
                  "企业名称",
                  style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
                  ),
                ),
                SizedBox(width: 15,),
                Expanded(
                  child: VgTextField(
                    controller: _companyNameController,
                    keyboardType: TextInputType.text,
                    style: TextStyle(
                        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                        fontSize: 14),
                    decoration: new InputDecoration(
                        counterText: "",
                        hintText: "请输入（30字内）",
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                            fontSize: 14,
                            color: Color(0XFFB0B3BF))),
                    inputFormatters: <TextInputFormatter> [
                      LengthLimitingTextInputFormatter(30)
                    ],
                    maxLines: 1,
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: 1,
            margin: EdgeInsets.only(left: 15),
          )
        ],
      ),
    );
  }


  ///通知更新
  _notifyChange() {
    _houseNumber = _houseNumberController?.text?.trim();
    _companyName = _companyNameController?.text?.trim();
    setState(() { });
  }

  ///创建
  Widget _toCreateWidget(){
    double width = (ScreenUtils.screenW(context) - 30 -9) / 2;
    if("01" == widget?.createOrEdit){
      width = (ScreenUtils.screenW(context) - 30);
    }
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15),
      height: 40,
      child: Row(
        children: [
          Visibility(
            visible: "00" == widget?.createOrEdit,
            child: _toSaveWidget(width),
          ),
          Visibility(
            visible: "00" == widget?.createOrEdit,
            child: SizedBox(width: 9,),
          ),
          _toSaveAndAddWidget(width),
        ],
      ),
    );
  }

  ///保存
  Widget _toSaveWidget(double width){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(StringUtils.isEmpty(_companyName)){
          return;
        }
        String floorflg = _floor?.contains("F")?"02":"01";
        String fnum = _floor?.replaceAll("F", "").replaceAll("B", "");
        if("00" == widget?.createOrEdit){
          _viewModel.createFloorCompany(context, widget?.buildingIndexId,
              _companyName, floorflg, fnum, _houseNumber, true);
        }else{
          _viewModel.editFloorCompany(context, _companyInfo?.id,
              _companyName, floorflg, fnum, _houseNumber, true);
        }

      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Container(
          height: 40,
          width: width,
          alignment: Alignment.center,
          color: Colors.white,
          child: Text(
            "保存",
            style: TextStyle(
                color: StringUtils.isNotEmpty(_companyName)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0xFFB0B3BF),
                fontSize: 15
            ),
          ),
        ),
      ),
    );
  }

  ///保存并继续添加
  Widget _toSaveAndAddWidget(double width){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(StringUtils.isEmpty(_companyName)){
          return;
        }
        String floorflg = _floor?.contains("F")?"02":"01";
        String fnum = _floor?.replaceAll("F", "").replaceAll("B", "");
        if("00" == widget?.createOrEdit){
          _viewModel.createFloorCompany(context, widget?.buildingIndexId,
              _companyName, floorflg, fnum, _houseNumber, false, callback: (){
                _houseNumberController.clear();
                _companyNameController.clear();
              });
        }else{
          _viewModel.editFloorCompany(context, _companyInfo?.id,
              _companyName, floorflg, fnum, _houseNumber, true);
        }
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Container(
          height: 40,
          width: width,
          alignment: Alignment.center,
          color: StringUtils.isNotEmpty(_companyName)?ThemeRepository.getInstance().getPrimaryColor_1890FF():Color(0xFFCFD4DB),
          child: Text(
            ("00" == widget?.createOrEdit)?"保存并继续添加":"保存",
            style: TextStyle(
                color: Colors.white,
                fontSize: 15
            ),
          ),
        ),
      ),
    );
  }

  List<String> getFloorList(){
    List<String> floorList = new List();
    floorList.addAll(getUpFloor());
    floorList.addAll(getDownFloor());
    return floorList;
  }

  List<String> getUpFloor(){
    List<String> upFloor = new List();
    upFloor.add("1F");
    upFloor.add("2F");
    upFloor.add("3F");
    upFloor.add("4F");
    upFloor.add("5F");
    upFloor.add("6F");
    upFloor.add("7F");
    upFloor.add("8F");
    upFloor.add("9F");
    upFloor.add("10F");


    upFloor.add("11F");
    upFloor.add("12F");
    upFloor.add("13F");
    upFloor.add("14F");
    upFloor.add("15F");
    upFloor.add("16F");
    upFloor.add("17F");
    upFloor.add("18F");
    upFloor.add("19F");
    upFloor.add("20F");

    upFloor.add("21F");
    upFloor.add("22F");
    upFloor.add("23F");
    upFloor.add("24F");
    upFloor.add("25F");
    upFloor.add("26F");
    upFloor.add("27F");
    upFloor.add("28F");
    upFloor.add("29F");
    upFloor.add("30F");

    upFloor.add("31F");
    upFloor.add("32F");
    upFloor.add("33F");
    upFloor.add("34F");
    upFloor.add("35F");
    upFloor.add("36F");
    upFloor.add("37F");
    upFloor.add("38F");
    upFloor.add("39F");
    upFloor.add("40F");

    upFloor.add("41F");
    upFloor.add("42F");
    upFloor.add("43F");
    upFloor.add("44F");
    upFloor.add("45F");
    upFloor.add("46F");
    upFloor.add("47F");
    upFloor.add("48F");
    upFloor.add("49F");
    upFloor.add("50F");

    upFloor.add("51F");
    upFloor.add("52F");
    upFloor.add("53F");
    upFloor.add("54F");
    upFloor.add("55F");
    upFloor.add("56F");
    upFloor.add("57F");
    upFloor.add("58F");
    upFloor.add("59F");
    upFloor.add("50F");

    upFloor.add("61F");
    upFloor.add("62F");
    upFloor.add("63F");
    upFloor.add("64F");
    upFloor.add("65F");
    upFloor.add("66F");
    upFloor.add("67F");
    upFloor.add("68F");
    upFloor.add("69F");
    upFloor.add("70F");

    upFloor.add("71F");
    upFloor.add("72F");
    upFloor.add("73F");
    upFloor.add("74F");
    upFloor.add("75F");
    upFloor.add("76F");
    upFloor.add("77F");
    upFloor.add("78F");
    upFloor.add("79F");
    upFloor.add("80F");

    upFloor.add("81F");
    upFloor.add("82F");
    upFloor.add("83F");
    upFloor.add("84F");
    upFloor.add("85F");
    upFloor.add("86F");
    upFloor.add("87F");
    upFloor.add("88F");
    upFloor.add("89F");
    upFloor.add("90F");

    upFloor.add("91F");
    upFloor.add("92F");
    upFloor.add("93F");
    upFloor.add("94F");
    upFloor.add("95F");
    upFloor.add("96F");
    upFloor.add("97F");
    upFloor.add("98F");
    upFloor.add("99F");
    upFloor.add("100F");


    upFloor.add("101F");
    upFloor.add("102F");
    upFloor.add("103F");
    upFloor.add("104F");
    upFloor.add("105F");
    upFloor.add("106F");
    upFloor.add("107F");
    upFloor.add("108F");
    upFloor.add("109F");
    upFloor.add("110F");

    upFloor.add("111F");
    upFloor.add("112F");
    upFloor.add("113F");
    upFloor.add("114F");
    upFloor.add("115F");
    upFloor.add("116F");
    upFloor.add("117F");
    upFloor.add("118F");
    upFloor.add("119F");
    upFloor.add("120F");
    int start = _comWbrandBean.usnum;
    int end = _comWbrandBean.uenum;
    if(start < 1){
      start = 1;
    }
    if(end < 1){
      end = 1;
    }
    return upFloor.sublist(start - 1, end).reversed.toList();
  }


  List<String> getDownFloor(){
    List<String> downFloor = new List();
    downFloor.add("B1");
    downFloor.add("B2");
    downFloor.add("B3");
    downFloor.add("B4");
    int start = _comWbrandBean.dsnum;
    int end = _comWbrandBean.denum;
    if(start < 1){
      start = 1;
    }
    if(end < 1){
      end = 1;
    }
    return downFloor.sublist(start - 1, end);
  }
}
